package com.yl.drug_management.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import com.yl.drug_management.config.RabbitMqConfig;
import com.yl.drug_management.pojo.StockOrder;
import com.yl.drug_management.service.OrderService;
import com.yl.drug_management.service.StockService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Date;

@Component
public class OrderMqReceiver {
    private static final Logger LOGGER = LoggerFactory.getLogger(OrderMqReceiver.class);

    @Autowired
    private StockService stockService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    //queues = RabbitMqConfig.QUEUE_NAME
    //@RabbitHandler
    //@Transactional 保证消费者的原子性
    //@RabbitListener(queues = "orderQueue")
    @RabbitListener(queues = "orderQueue")
    public void process(String message) {
        LOGGER.info("OrderMqReceiver收到消息开始用户下单流程"+ message);
        JSONObject jsonObject = JSONObject.parseObject(message);
        try {
            // 查询消息处理表,已处理过就直接返回否则处理消息并写入处理表，防止重复消费
            Integer count = orderService.findMqMessageHandle(jsonObject.getInteger("sid"), jsonObject.getInteger("userId"));
            if (count == 0) { // 未处理过消息，写入消息记录已处理过
                orderService.writeMqMessageHandle(jsonObject.getInteger("sid"), jsonObject.getInteger("userId"));
            } else { //  已处理过消息，直接返回
                LOGGER.info("该消息已经处理过了");
                return;
            }
            // 下单
            StockOrder order_id = orderService.createOrderByMq(jsonObject.getInteger("sid"), jsonObject.getInteger("userId"));
            if (order_id == null) {
                throw new Exception("下单异常");
            }
            // 修改消息发送表，将处理状态修改为已处理
            orderService.updateMqMessage(jsonObject.getInteger("sid"), jsonObject.getInteger("userId"));

            // 下单后向延迟队列中发送消息，判断是否支付，决定是否取消订单
            // 发送消息到延迟队列,延迟时间为30分钟
            LOGGER.info("向延迟队列中发送了订单消息，延迟30分钟消费");
            //Message msg = MessageBuilder.withBody(JSONObject.toJSONString(order_id).getBytes(StandardCharsets.UTF_8)).setHeader("x-delay",  3 * 1000).build();
            rabbitTemplate.convertAndSend(RabbitMqConfig.EXCHANGE_NAME, RabbitMqConfig.QUEUE_NAME, order_id.getId()+","+order_id.getSid(),(msg -> {
                msg.getMessageProperties().setDelay(3000);
                return msg;
            }));

        } catch (Exception e) {
            LOGGER.error("消息处理异常：",e);
        }
    }

    @RabbitListener(queues = RabbitMqConfig.QUEUE_NAME,containerFactory = "rabbitListenerContainerFactory")
    public void getIfPay(Message message) {
        // 查询订单是否支付，已支付则成功创建，否则该订单未支付成功，逻辑删除
        LOGGER.info("开始处理订单是否支付成功");
        //JSONObject jsonObject = new JSONObject();
        //StockOrder order = JSONObject.parseObject(new String(message.getBody()),StockOrder.class);
        //StockOrder object = JSONObject.parseObject(new String(message.getBody()),StockOrder.class);
        //System.out.println("message:"+ new String(message.getBody()));
        String s = new String(message.getBody());
        StockOrder order = new StockOrder();

        //System.out.println(s.split(",")[0].substring(1));
        //System.out.println(s.split(",")[1].substring(0,s.split(",")[1].length()-1));
        order.setId(Integer.parseInt(s.split(",")[0].substring(1)));
        order.setSid(Integer.parseInt(s.split(",")[1].substring(0,s.split(",")[1].length()-1)));
        System.out.println(order.getId());
        Integer status =  orderService.getOrderStatus(order.getId());
        if (status == 1) { // 支付成功
            LOGGER.info("订单支付成功，抢购成功");
        } else { // 订单支付失败，置订单状态为-1，逻辑删除该订单
            LOGGER.info("订单支付失败，回退库存，并且修改该订单状态为-1");
            orderService.orderNotPay(order);
        }
    }
}
